<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/12
 * Time: 10:48
 */

namespace app\admin\controller;


use app\admin\service\CategoryService;
use app\lib\exception\MysqlErrorException;
use think\facade\Request;
use app\admin\model\Category as CategoryModel;

class Category extends BaseController
{
    #
    public function index()
    {
        return $this->fetch('category/category');
    }
    # 添加或者更新分类
    public function addCategory($id = '')
    {
        if($id){
            $info = CategoryModel::findOne($id);
            $this->assign('info',$info);
        }
        return $this->fetch('category/addCategory');
    }

    /**
     * 返回category表中所有的数据并进行分页
     * @param $page int 页数
     * @param $limit int 每页数量
     * @return \think\response\Json
     */
    public function getAllCategory($page,$limit)
    {
        $model = new CategoryModel();
        $layuiPage = new \Page\Page($model,$page,$limit,[],[]);
        $result = $layuiPage->layuiPage();
        return json($result);
    }
    /** 添加或者更新分类，如果category_id存在则更新，不存在则添加
     * $post_data 获取所有post参数
     */
    public function addOrUp()
    {
        $post_data = Request::post();
        $service = new CategoryService();
        if($post_data['category_id']){
            $result = $service->upCategory($post_data);
            if(!$result){
                return $this->error('更新失败(分类名称可能不存在)');
            }
            return $this->success('更新成功','/admin/Category/index');
        }else {
            $result = $service->addCategory($post_data);
            if(!$result){
                return $this->error('添加失败(分类名称可能存在)');
            }
            return $this->success('添加成功','/admin/Category/index');
        }
    }
    public function delCategory()
    {
        $category_id = Request::post('category_id');
        $resule = CategoryModel::delOne($category_id);
        if (!$resule){
            throw new MysqlErrorException([
                'code' => 300,
                'msg' => '删除失败'
            ]);
        }
        return json([
            'code' => 200
        ]);
    }
}